package com.becca.cake.service.advert.impl;

import java.io.File;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.becca.cake.core.exception.ServiceException;
import com.becca.cake.core.qiniu.FileNameRuleHelp;
import com.becca.cake.core.qiniu.QiNiuGoodsPicTemplate;
import com.becca.cake.core.qiniu.bean.QiNiuResponse;
import com.becca.cake.dao.advert.AdvertDAO;
import com.becca.cake.model.advert.AdvertModel;
import com.becca.cake.model.goods.GoodsPictureModel;
import com.becca.cake.model.system.AdminDO;
import com.becca.cake.service.advert.IAdvertService;
import com.becca.cake.util.JsonUtil;
import com.becca.cake.util.StringUtil;

/**
 * 广告管理service实现类
 * @copyright  尊星(上海)信息科技有限公司
 * @author 
 * @date 2016年5月27日 下午4:09:34
 */
@Service
public class AdvertServiceImpl implements IAdvertService {
    @Autowired
    private AdvertDAO advertDAO;

    @Override
    public List<AdvertModel> selectAdverts(Map<String, Object> map) throws ServiceException {
        return this.advertDAO.selectAdverts(map);
    }

    @Override
    public Long selectAdvertsCount(Map<String, Object> map) throws ServiceException {
        return this.advertDAO.selectAdvertsCount(map);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void insertOrUpdateAdvert(AdvertModel advertModel, MultipartFile files,
                                     String fileTempPath, AdminDO adminDo) throws Exception {

        // 1.step 根据 来源类型 设置数据来源  
        if (advertModel.getAdvSourceType() == AdvertModel.ADV_COMBO_SOURCE
            && StringUtil.isNotEmpty(advertModel.getAdvComboSource())) {
            advertModel.setAdvSource(advertModel.getAdvComboSource());
        } else if (advertModel.getAdvSourceType() == AdvertModel.ADV_TEXT_SOURCE
                   && StringUtil.isNotEmpty(advertModel.getAdvTextSource())) {
            advertModel.setAdvSource(advertModel.getAdvTextSource());
        }

        // 2.step 广告数据校验
        AdvertModel.validInsertOrUpdateAdvert(advertModel, files);

        // 3.step 上传图片
        String advertPicPath = "";
        if (!files.isEmpty()) {
            //step3:重新生成图片文件名
            String fileName = FileNameRuleHelp.getGoodsPictureFileName() + "."
                              + FilenameUtils.getExtension(files.getOriginalFilename());
            String filePath = fileTempPath + File.separator + fileName;
            File localFile = new File(filePath);
            files.transferTo(localFile);
            //step4:调用七牛上传图片
            QiNiuResponse response = QiNiuGoodsPicTemplate.uploadFile(localFile, fileName);
            if (response.isSuccess()) {
                advertPicPath = QiNiuGoodsPicTemplate.getDownloadUrl(response.key);
            } else {
                throw new ServiceException(GoodsPictureModel.PICTURE_UPDLOAD_FAILED);
            }
            // step5:删除本地图片
            localFile.delete();
        }
        if (StringUtils.isNotEmpty(advertPicPath)) {
            advertModel.setAdvPicPath(advertPicPath);
        }
        if (advertModel.getAdvStatus() == null) {
            advertModel.setAdvStatus(AdvertModel.ADV_STATUS_NOMAL);
        }
        // step6:添加或修改广告
        if (advertModel.getId() == null) {// 新增
            advertModel.setCreatedName(adminDo.getTrueName());
            this.advertDAO.insertAdvert(advertModel);
        } else {// 修改
            advertModel.setUpdatedName(adminDo.getTrueName());
            this.advertDAO.updateAdvert(advertModel);
        }

    }

    @Override
    public AdvertModel selectAdvertById(Integer advertId) {
        AdvertModel.validAdvId(advertId);
        return this.advertDAO.selectAdvertById(advertId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void updateAdvStatusById(Map<String, Object> map) throws ServiceException {
        Integer advertId = Integer.valueOf(map.get("advertId").toString());
        String status = String.valueOf(map.get("status"));
        // 1.step 校验
        AdvertModel.validAdvStatus(advertId, status);
        AdvertModel am = this.advertDAO.selectAdvertById(advertId);
        String advNowStatus = am.getAdvStatus().toString();
        if (status.equals(advNowStatus)
            && AdvertModel.ADV_STATUS_FORBIDDEN.toString().equals(status)) {
            throw new ServiceException(AdvertModel.ADVERT_STATUS_FORBIDDEN_EXIST);
        } else if (status.equals(advNowStatus)
                   && AdvertModel.ADV_STATUS_NOMAL.toString().equals(status)) {
            throw new ServiceException(AdvertModel.ADVERT_STATUS_NOMAL_EXIST);
        }
        // 2.step 修改广告状态
        this.advertDAO.updateAdvStatusById(map);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void updateOrders(String jsonList) throws Exception {
        List<AdvertModel> list = JsonUtil.returnObjectList(jsonList, AdvertModel.class);
        AdvertModel.validUpdateOrders(list);
        this.advertDAO.updateOrders(list);
    }
}
